package com.atguigu.web;

import com.atguigu.pojo.Book;
import com.atguigu.pojo.Page;
import com.atguigu.service.BookService;
import com.atguigu.service.impl.BookServiceImpl;
import com.atguigu.utils.WebUtils;
import com.sun.javaws.exceptions.BadVersionResponseException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author YAO
 * @create 2021-04-28 19:49
 */
@WebServlet(name = "BookServlet", value = "/manager/bookServlet")
public class BookServlet extends BaseServlet{

    private BookService bookService = new BookServiceImpl();
    private final String LOCALPATH = "D:\\myWorkSpace\\javaProjects\\javaweb\\book" +
            "\\src\\main\\webapp\\static\\img\\";

    /**
     * 处理分页功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.获取请求的参数 pageNo pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"),1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        // 2.调用bookService.page() 返回page对象
        Page<Book> page = bookService.page(pageNo, pageSize);

        page.setUrl("manager/bookServlet?action=page");

        // 3.保存page对象到request域中
        req.setAttribute("page",page);
        // 4.请求转发到page/manager/book_manager.jsp
        req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);

    }


    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HashMap<String, Object> formMap = null;
        // 1.先判断上传的数据是否多段数据 （只有是多段的数据，才是文件上传的）
        if(ServletFileUpload.isMultipartContent(req)){
            //创建FileItemFactory工厂实现类
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
            //创建一个map用于保存表单项的数据
            formMap = new HashMap<>();
            //解析上传的数据，得到每一个表单项FileItem
            try {
                List<FileItem> list = upload.parseRequest(req);

                //循环判断每一个表单项是普通类型还是上传的文件
                for (FileItem fileItem : list) {
                    if(fileItem.isFormField()){
                        //普通表单项
                        String fieldName = fileItem.getFieldName();
                        //参数UTF-8解决乱码问题
                        String fieldValue = fileItem.getString("UTF-8");
                        formMap.put(fieldName,fieldValue);
                    }else {
                        //上传的文件
                        String imgName = fileItem.getName();
                        if("".equals(imgName) || imgName == null){
                            //如果图片路径为空,直接返回
                            break;
                        }
                        formMap.put(fileItem.getFieldName(),"static/img/" + imgName);
                        fileItem.write(new File(LOCALPATH + imgName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"),0);
        pageNo+=1;
        // 1. 获取请求的参数==封装成为Book对象
        Book book = WebUtils.copyParamToBean(formMap, Book.class);
//        // 2. 调用BookService.addBook()保存图书
        bookService.addBook(book);
        // 3. 跳到图书列表页面
        resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=page&pageNo=" + pageNo);

    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取请求的参数图书id
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        //获取图书的图片路径
        Book book = bookService.queryBookById(id);
        String img_path = book.getImg_path();
        img_path = LOCALPATH + img_path.split("/")[2];
        //删除该图片
        if(!book.getImg_path().contains("default.png")){
            new File(img_path).delete();
        }
        //2. 调用bookService.deleteBookById();删除图书
        bookService.deleteBookById(id);
        //3. 重定向回图书列表管理页面
        //      /book/manager/bookServlet?action=list
        resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=page&pageNo=" + req.getParameter("pageNo"));

    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HashMap<String, Object> formMap = null;
        // 1.先判断上传的数据是否多段数据 （只有是多段的数据，才是文件上传的）
        if(ServletFileUpload.isMultipartContent(req)){
            //创建FileItemFactory工厂实现类
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
            //创建一个map用于保存表单项的数据
            formMap = new HashMap<>();
            //解析上传的数据，得到每一个表单项FileItem
            try {
                List<FileItem> list = upload.parseRequest(req);

                //循环判断每一个表单项是普通类型还是上传的文件
                for (FileItem fileItem : list) {
                    if(fileItem.isFormField()){
                        //普通表单项
                        String fieldName = fileItem.getFieldName();
                        //参数UTF-8解决乱码问题
                        String fieldValue = fileItem.getString("UTF-8");
                        formMap.put(fieldName,fieldValue);
                    }else {
                        //上传的文件
//                        System.out.println("表单项的name属性值：" + fileItem.getFieldName());
//                        System.out.println("上传的文件名：" + fileItem.getName());
                        String imgName = fileItem.getName();
                        if("".equals(imgName) || imgName == null){
                            //如果图片路径为空，说明不修改,图片路径为原路径，直接退出循环
                            formMap.put(fileItem.getFieldName(),req.getParameter("imgPath"));
                            break;
                        }
                        formMap.put(fileItem.getFieldName(),"static/img/" + imgName);
                        fileItem.write(new File(LOCALPATH + imgName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //设置bookId
        String bookId = req.getParameter("id");
        //添加进map中
        formMap.put("id",bookId);

        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"),0);
        pageNo+=1;
        // 1. 获取请求的参数==封装成为Book对象
        Book book = WebUtils.copyParamToBean(formMap, Book.class);
        //2. 调用BookService.updateBook(book);修改图书
        bookService.updateBook(book);
        //3. 重定向回图书列表管理页面
        //地址：/工程名/manager/bookServlet?action=list
        resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=page&pageNo="
                + req.getParameter("pageNo"));
    }

    protected void getBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取请求的参数图书编号
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        //2. 调用bookService.queryBookById查询图书
        Book book = bookService.queryBookById(id);
        //3. 保存到图书Request域中
        req.setAttribute("book",book);
        //4. 请求转发到 pages/manager/book_edit.jsp页面
        req.getRequestDispatcher("/pages/manager/book_edit.jsp").forward(req,resp);
    }

    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 通过BookService查询全部图书
        List<Book> bookList = bookService.queryBooks();
        // 全部图书保存到request域中
        req.setAttribute("books",bookList);
        // 请求转发到/pages/manager/book_manager.jsp
        req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);
    }

}
